package com.td.erhome.ui.min;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.acker.simplezxing.activity.CaptureActivity;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.td.erhome.R;
import com.td.erhome.adapter.CouponListAdapter;
import com.td.erhome.base.BaseActivity;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.CouonBaen;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.utils.DisplayUtil;
import com.td.erhome.utils.T;
import com.td.erhome.utils.TextUtil;
import com.td.erhome.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 我的优惠券
 */
public class MyCouponActivity extends BaseActivity {

    @Bind(R.id.img_back)
    ImageView mImgBack;
    @Bind(R.id.tv_dh)
    TextView mTvDh;
    @Bind(R.id.et_serch)
    TextView mEtSerch;
    @Bind(R.id.tv_account_balance)
    TextView mTvAccount;
    @Bind(R.id.recyclview)
    XRecyclerView mRecyclerView;
    int page = 1;
    private CouponListAdapter mAdapter;
    private List<CouonBaen.BalanceListBean> mCoupon_list = new ArrayList<>();
    private int mTotal_count;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_coupon;
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new CouponListAdapter(mCoupon_list,this);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mAdapter.clearData();
                page =1;
                getAmountdetail();
            }
            @Override
            public void onLoadMore() {
                if (mAdapter.mCoupon_list.size()<mTotal_count){
                    page++;
                    getAmountdetail();
                }
                else {
                    mRecyclerView.refreshComplete();
                }
            }
        });

        getAmountdetail();

    }

    @Override
    protected void releaseResource() {

    }

    @OnClick({R.id.img_back, R.id.tv_dh,R.id.et_serch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_dh:
                createDia();
                break;
            case R.id.et_serch:
                startActivityForResult(new Intent(this, CaptureActivity.class), CaptureActivity.REQ_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
                        String[] split = data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT).split("&");
                        scanQrcode(split[0],split[1]);
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            // for some reason camera is not working correctly
                            String[] split1 = data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT).split("&");
                            scanQrcode(split1[0],split1[1]);
                        }
                        break;
                }
                break;
        }
    }

    //扫描推广人员二维码获得金额
    public void scanQrcode(String spreader_id,String spreader_hash){
        HashMap<String, Object> params = new HashMap<>();
        params.put("spreader_id", spreader_id);
        params.put("spreader_hash", spreader_hash);
        Api.getRetrofit().scanQrcode(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(MyCouponActivity.this){
                    @Override
                    public void onNext(BaseBean couonBaenBaseBean) {
                        super.onNext(couonBaenBaseBean);
                        mAdapter.clearData();
                        page =1;
                        getAmountdetail();
                    }
                });
    }

    //抵扣
   public void deductAmount(String amount){

       HashMap<String, Object> params = new HashMap<>();
       params.put("amount", amount);
       Api.getRetrofit().deductAmount(params)
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new BaseSubscriber<BaseBean>(MyCouponActivity.this){
                   @Override
                   public void onNext(BaseBean baseBean) {
                       super.onNext(baseBean);
                       mAdapter.clearData();
                       page =1;
                       getAmountdetail();
                   }
               });
   }

    //获得优惠券列表
    public void getAmountdetail(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", UserManager.getIns().getUser().uid+"");
        params.put("page", page);
        Api.getRetrofit().getAmountdetail(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean<CouonBaen>>(MyCouponActivity.this){
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mRecyclerView.refreshComplete();
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mRecyclerView.refreshComplete();
                    }
                    @Override
                    public void onNext(BaseBean<CouonBaen> couonBaenBaseBean) {
                        super.onNext(couonBaenBaseBean);
                        mCoupon_list = couonBaenBaseBean.getData().balance_list;
                        mTotal_count = couonBaenBaseBean.getData().total_count;
                        mAdapter.addData(mCoupon_list);
                        mRecyclerView.refreshComplete();
                        mTvAccount.setText("￥"+couonBaenBaseBean.getData().account_balance);
                    }
                });
    }


    //抵扣
    public  void createDia() {

        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.edt_dialog, null);

        final EditText etMount = (EditText)v.findViewById(R.id.et_mount);
        TextView tvCans = (TextView)v.findViewById(R.id.tv_cans);
        TextView tvSure = (TextView)v.findViewById(R.id.tv_sure);

        etMount.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        // 创建自定义样式dialog
        final Dialog mLoadingDialog = new Dialog(this, R.style.loading_dialog);
        mLoadingDialog.setCancelable(true);// 可以用"返回键"取消
        mLoadingDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        mLoadingDialog.setContentView(v, new LinearLayout.LayoutParams(DisplayUtil.dip2px(this,200),
                DisplayUtil.dip2px(this,130)));

        Window window = mLoadingDialog.getWindow();
        window.setGravity(Gravity.CENTER);  //此处可以设置dialog显示的位置
        mLoadingDialog.show();

        tvCans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isEditTextEmpty(etMount)){
                    T.showLong(MyCouponActivity.this,"请输入抵扣金额");
                    return;
                }
                deductAmount(etMount.getText().toString());
                mLoadingDialog.dismiss();
            }
        });


    }


}
